package net.gxnun.xiaoyuan.core.annotaction.handler;

import java.util.HashMap;
import java.util.Map;

import net.gxnun.xiaoyuan.core.annotaction.MessageMapping;
import net.gxnun.xiaoyuan.core.message.handler.MessageHandler;
import net.gxnun.xiaoyuan.core.share.ApplicationContextHolder;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class MessageMappingHandler {
    
    
    public MessageMappingHandler(){
        determineUrlsForHandler();
    }
    
    private Map<String,MessageHandler> cachedMappings = new HashMap<String,MessageHandler>();
    private Map<String,String> msgTypeCachedMappings = new HashMap<String,String>();
    
    /**
     * 扫描具有MessageMapping注解的类
     */
    private void determineUrlsForHandler(){
        ApplicationContext context = ApplicationContextHolder.getApplicationContext();
        Map<String,Object> map = context.getBeansWithAnnotation(MessageMapping.class);
        
        for(String key : map.keySet()){
            MessageMapping messageMapping = context.findAnnotationOnBean(key, MessageMapping.class);
            String[] urls = messageMapping.value();
            for(String url : urls){
                cachedMappings.put(url, (MessageHandler)map.get(key));
                
                //获取允许的类型
                StringBuffer sb = new StringBuffer();
                for(String type : messageMapping.msgType()){
                    sb.append(type);
                }
                msgTypeCachedMappings.put(url, sb.toString());
            }
        }
    }
    
    public MessageHandler getMessageHandler(String url){
        return cachedMappings.get(url);
    }
    
    public String getAllowType(String url){
        return msgTypeCachedMappings.get(url);
    }
    
}
